<?php
/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2016/10/31
 * Time: 23:20
 */

namespace App\Utils;

use App\Http\C5\C5ResponseFactory;
use App\Models\ExplorerFile;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Readers\LaravelExcelReader;
use p5\objects\PropertyUtils;

class ExcelReader
{
    private $data = [];

    public function loadData($file, $rows = 0)
    {
        if (!empty($file)) {
            Excel::selectSheetsByIndex(0)->load($file, function ($reader) use ($rows) {
                /**
                 * @var $reader LaravelExcelReader
                 */
                $reader->noHeading();
                $temp = null;
                if ($rows <= 0) {
                    $temp = $reader->all();
                } else {
                    $temp = $reader->take($rows)->all();
                }
                $this->data = json_decode(json_encode($temp), true);
                return;
            });
        }
        // echo json_encode($this->data);
        $this->data = self::toHashList($this->data);
        return $this->data;
    }

    /**
     * 以第一行为 key，转出成 hash格式
     * @param $data
     * @return array
     */
    static public function toHashList($data)
    {
        if (empty($data)) {
            return [];
        }
        $size = count($data);
        $result = [];
        $titles = array_values($data[0]);
        if ($size > 1) {
            for ($i = 1; $i < $size; $i++) {
                $line = $data[$i];
                $values = self::toSimpleValues($line);
                $matrix = array_combine($titles, $values);
                array_push($result, $matrix);
            }
        }
        return $result;
    }

    static public function toSimpleValues($line)
    {
        if (is_object($line)) {
            $line = json_decode(json_encode($line), true);
        }
        $matrix = [];
        $values = array_values($line);
        $cols = count($values);
        for ($n = 0; $n < $cols; $n++) {
            $value = $values[$n];
            array_push($matrix, self::getCellValue($value));
        }
        return $matrix;
    }

    static public function getLineValue($line, $index)
    {
        $key = $line . "";
        $value = PropertyUtils::get($line, $key, "");
        return self::getCellValue($value);
    }

    static public function getCellValue($value)
    {
        if (is_string($value)) {
            return $value;
        }
        if (is_array($value)) {
            if (array_key_exists("date", $value)) {
                return $value["date"];
            }
        }
        if (is_object($value) || is_array($value)) {
            Log::error("读取Excel，发现不可解析的数据单元:" . json_encode($value));
            return json_encode($value);
        }
        return $value;
    }
}